/*import 'package:flutter/material.dart';
import 'package:safety_platform/utils.dart';
import 'package:flutter_calendar/flutter_calendar.dart';
import 'package:date_utils/date_utils.dart';
import 'package:safety_platform/theme.dart';
import 'package:safety_platform/models/task.dart';
import 'package:safety_platform/models/user.dart';
import 'package:safety_platform/models/task_history.dart';
import 'package:safety_platform/pages/task/services.dart';
import 'package:modal_progress_hud/modal_progress_hud.dart';
import 'package:flutter_spinkit/flutter_spinkit.dart';
import 'package:safety_platform/pages/task/task_report.dart';


class TaskHistoryPage extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    // TODO: implement createState
    return _TaskHistoryState();
  }
}

class _TaskHistoryState extends State<TaskHistoryPage> {
  DateTime _selectedDate;
  int _currentMonth;
  Map<String, String> _data;

  List<Task> _taskData;
  bool _isFetchingRange;
  // String _currentDataKey;
  DateTime _frist;
  DateTime _last;
  Map<String, List<Task>> _tasksOfDate;

  List<String> s = <String>['risky', 'pending', 'done'];

  @override
  void dispose() {
    super.dispose();
    _data.clear();
    _tasksOfDate.clear();
    _data = null;
    _tasksOfDate = null;
  }

  @override
  void initState() {
    _selectedDate = DateTime.now();
    _currentMonth = _selectedDate.month;
    _data = new Map();
    _tasksOfDate = new Map();
    _isFetchingRange = false;

    List<DateTime> days = Utils.daysInMonth(_selectedDate);

    _frist = days.first;
    _last = days.last;

    // for (DateTime day in Utils.daysInMonth(_selectedDate)) {
    //   int i = Random().nextInt(5) - 3;
    //   _data['${day.year}-${day.month}-${day.day}'] = i < 0 ? '' : s[i];
    // }
    _fetchData();
    _fetchTaskList(_selectedDate);
    super.initState();
  }

  _calcStatus(List<Task> tasks) {
    if (tasks == null) {
      return '';
    }
    if (tasks.any((t) => t.status == 'risky')) {
      return 'risky';
    }
    if (tasks.any((t) => t.status == 'pending')) {
      return 'pending';
    }
    return 'done';
  }

  _fetchTaskList(DateTime day) {
    String date = Utils.apiDayFormat(day);

    if (_tasksOfDate.containsKey(date)) {
      setState(() {
        _taskData = _tasksOfDate[date];
      });
      return;
    }
    // setState(() {
    //       _isFetchingRange = true;
    //     });
    getTaskList(created: day).then((page) {
      if (page.count > 0) {
        if (Utils.isSameDay(day, _selectedDate)) {
          setState(() {
            // _selectedDate = day;
            // _isFetchingRange=false;
            _tasksOfDate[Utils.apiDayFormat(day)] = page.results;
            _taskData = page.results;
          });
        }
      }
    });
  }

  _fetchData() {
    _isFetchingRange = true;
    getTaskHistoryList(startDate: _frist, endDate: _last).then((page) {
      print('拉取范围历史数据 start:[$_frist] end:[$_last] data:${page}');
      int count = page.count;
      List<TaskHistory> results = page.results;
      setState(() {
        _isFetchingRange = false;
        _data.clear();
        for (TaskHistory history in results) {
          _data[Utils.apiDayFormat(history.date)] = _calcStatus(history.tasks);
        }
      });
    });
  }

  _onSelectedRangeChange(range) {
    if (Utils.isSameDay(range.item1, _frist) &&
        Utils.isSameDay(range.item2, _last)) {
      print('范围未改变，无需重新拉取数据');
      return;
    }
    _frist = range.item1;
    _last = range.item2;
    _fetchData();
  }

  String _getDataKey(day) {}
  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return Scaffold(
        appBar: AppBar(
          // leading: appLeading(context),
          title: Text('检查任务'),
          elevation: 0,
          backgroundColor: Theme.of(context).primaryColor,
          centerTitle: true, //设置标题是否局中
        ),
        body: ModalProgressHUD(
          child: _body(),
          inAsyncCall: _isFetchingRange,
          progressIndicator: Container(
            height: 60,
            width: 60,
            color: Colors.black,
            child: SpinKitWave(color: Colors.white, size: 24),
          ),
        ));
  }

  TextStyle _configureDateStyle(notInMonth, bool isSelected) {
    TextStyle dateStyles;
    //if (isExpanded) {
    if (isSelected) {
      dateStyles = TextStyle(color: Colors.white);
    } else {
      dateStyles = notInMonth
          ? new TextStyle(color: Colors.black)
          : new TextStyle(color: Colors.black38);
    }
    //} else {
    //  dateStyles = new TextStyle(color: Colors.black);
    //  }
    return dateStyles;
  }

  handleNewDate(date) {
    // print(Utils.daysInMonth(date));
    List<DateTime> range = Utils.daysInMonth(date);
    print(
      '当前开始时间 $_frist, $_last, ${range.first}, ${range.last}, $date',
    );
    if (Utils.isSameDay(range.first, _frist) &&
        Utils.isSameDay(range.last, _last)) {
      print('日期改变，范围未变，直接从缓存拉取数据');
      String key = Utils.apiDayFormat(date);

      List<Task> tasks = List();
      if (_data.containsKey(key)) {
        // 有数据
        if (_tasksOfDate.containsKey(key)) {
          // 缓存中有数据
          tasks = _tasksOfDate[key];
        } else {
          // 缓存中没有，得去拿数据
          _fetchTaskList(date);
        }
      }
      setState(() {
        _selectedDate = date;
        _taskData = tasks;
      });
    } else {
      setState(() {
        _selectedDate = date;
        _frist = range.first;

        _last = range.last;
      });
      _fetchData();
      _fetchTaskList(date);
    }

    // _fetchTaskList(date);
  }

  Color _getStatusColorByDay(DateTime day) {
    String status = _data[Utils.apiDayFormat(day)];
    return _getStatusColor(status);
  }

  Color _getStatusColor(String status) {
    switch (status) {
      case 'risky':
        return riskyColor;
      case 'done':
        return doneColor;
      case 'pending':
        return pendigColor;
      default:
        return null;
    }
  }

  Widget buildTaskWidget(BuildContext context, int index) {
    String key = Utils.apiDayFormat(_selectedDate);

    List<Task> tasks = _tasksOfDate[key];
    if (tasks == null) {
      return Container();
    }

    Task task = tasks[index];

    User userOfExecution = task.userOfExecution;
    String userName = userOfExecution == null? '无' : userOfExecution.screenName;
    return InkWell(
      
      onTap: () {
        if (task.status != 'pending') {
          Navigator.of(context).push(MaterialPageRoute(builder: (context) => TaskReportPage(task)));
        }
      },
      child: Card(
        // margin: EdgeInsets.all(8),
        color: Colors.white,
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: <Widget>[
            Padding(
              child: Text(
                '风险点名称: ${task.risk.name}',
              ),
              padding: EdgeInsets.all(8),
            ),
            Container(
              padding: EdgeInsets.all(8),
              color: Theme.of(context).primaryColor,
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: <Widget>[
                  Text(
                    '风险类型: ${task.risk.classification.join(",")}',
                    style: TextStyle(color: Colors.white),
                  ),
                  Divider(
                    color: Colors.transparent,
                    height: 8,
                  ),
                  Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: <Widget>[
                      Text.rich(
                        TextSpan(
                          text: '检查结果:',
                          style: TextStyle(
                            color: Colors.white,
                          ),
                          children: <TextSpan>[
                            TextSpan(
                                text: taskStatusTransform(task.status),
                                style: TextStyle(
                                    color: _getStatusColor(task.status))),
                          ],
                        ),
                      ),
                      // Text(
                      //   '检查结果:已检查',
                      //   style: TextStyle(color: _getStatusColor(task.status)),
                      // ),
                      Text('检查人员:$userName', style: TextStyle(color: Colors.white)),
                    ],
                  ),
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }

  Widget _body() {
    // Event
    return new Container(
      margin: new EdgeInsets.symmetric(
        horizontal: 5.0,
        // vertical: 10.0,
      ),
      child: new Column(
        // shrinkWrap: true,
        mainAxisSize: MainAxisSize.min,
        children: <Widget>[
          // new Calendar(
          //   onSelectedRangeChange: (range) =>
          //       print("Range is ${range.item1}, ${range.item2}"),
          //   onDateSelected: (date) => handleNewDate(date),
          // ),
          // new Divider(
          //   height: 50.0,
          // ),
          // new Text('The Expanded Calendar:'),
          new Calendar(
            onDateSelected: (date) => handleNewDate(date),
            onSelectedRangeChange: (range) {
              print('range item1 ${range.item1} item2 ${range.item2}');
              _onSelectedRangeChange(range);
            },
            // print("Range is ${range.item1}, ${range.item2}"),
            isExpandable: true,
            showTodayAction: false,
            showCalendarPickerIcon: false,
            dayBuilder: (BuildContext context, DateTime day) {
              // print('dayBuilder $day');
              // print(_data[day]);
              // print(_data);
              bool notInMonth = true;
              if (day.month != _currentMonth) {
                notInMonth = false;
              }
              Center statusWidget;

              Color themeColor = Theme.of(context).primaryColor;

              Color statusColor = _getStatusColorByDay(day);

              if (statusColor != null) {
                themeColor = statusColor;
                statusWidget = Center(
                  child: Container(
                    width: 8,
                    height: 2,
                    color: themeColor,
                  ),
                );
              } else {
                statusWidget = Center(
                  child: Container(
                    width: 8,
                    height: 2,
                    // color: pendigColor,
                  ),
                );
              }
              return Container(
                color: Colors.white,
                padding: EdgeInsets.all(4),
                child: Container(
                  padding: EdgeInsets.all(4),
                  decoration: Utils.isSameDay(day, _selectedDate)
                      ? new BoxDecoration(
                          shape: BoxShape.circle,
                          color: themeColor,
                        )
                      : new BoxDecoration(),
                  // color: Colors.white,
                  child: Column(
                    children: <Widget>[
                      Expanded(
                        child: Container(
                          alignment: Alignment.center,
                          child: Text(
                            day.day.toString(),
                            style: _configureDateStyle(notInMonth,
                                Utils.isSameDay(day, _selectedDate)),
                          ),
                        ),
                      ),
                      statusWidget,
                    ],
                  ),
                ),
              );
            },
          ),

          // buildTaskWidget(),
          // buildTaskWidget(),
          // buildTaskWidget(),
          // buildTaskWidget(),
          // buildTaskWidget(),
          Expanded(
            child: Container(
              height: double.infinity,
              child: ListView.builder(
                // shrinkWrap: true,
                itemCount: _taskData == null ? 0 : _taskData.length,
                itemBuilder: (BuildContext context, int i) =>
                    buildTaskWidget(context, i),
                // itemCount: 230,

                //     buildTaskWidget(),
                // buildTaskWidget(),
                // buildTaskWidget(),
                // buildTaskWidget(),
                // buildTaskWidget(),
              ),
            ),
          ),
        ],
      ),
    );

//       margin: EdgeInsets.symmetric(horizontal: 8.0),
//       child: CalendarCarousel(
//        // current: DateTime.now(),
//         // onDayPressed: (DateTime date) {
//         //   this.setState(() => _currentDate = date);
//         // },
//         locale: 'zh-CN',
//         thisMonthDayBorderColor: Colors.grey,
//         height: 420.0,
//      //   selectedDateTime: _currentDate,
//         // daysHaveCircularBorder: false,
//         dayPadding:0.0,
//         showHeaderButton: false,
//         headerMargin: EdgeInsets.symmetric(vertical: 4),
//         daysHaveCircularBorder: null,
//         // daysTextStyle: TextStyle(

//         // )
//         /// null for not rendering any border, true for circular border, false for rectangular border
//     //    markedDatesMap: _markedDateMap,
// //          weekendStyle: TextStyle(
// //            color: Colors.red,
// //          ),
// //          weekDays: null, /// for pass null when you do not want to render weekDays
// //          headerText: Container( /// Example for rendering custom header
// //            child: Text('Custom Header'),
// //          ),
//       ),
//     );
  }
}
*/